package com.by.toolkit.utils;

import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Tian Wei
 * @version 1.0
 * @date 2024/4/23 11:57 AM
 */
public class ByMobileUtils {

    /**
     * 手机号基本工具类
     */
    private final static PhoneNumberUtil PHONE_NUMBER_UTIL = PhoneNumberUtil.getInstance();

    /**
     *
     */
    private final static PhoneNumberOfflineGeocoder GEO_CODER = PhoneNumberOfflineGeocoder.getInstance();

    /**
     * 验证当前手机号是否有效
     *
     * @param phone 手机号
     * @return 校验结果
     */
    public static boolean isValidNumber(String phone) {
        return PHONE_NUMBER_UTIL.isValidNumber(getChinaPhoneNumber(phone));
    }

    /**
     * 获取手机号归属地
     *
     * @param phone 手机号
     * @return 归属地
     */
    public static String getChinaRegionInfoStrByPhone(String phone) {
        return isValidNumber(phone) ? GEO_CODER.getDescriptionForNumber(getChinaPhoneNumber(phone), Locale.CHINESE) : "";
    }

    /**
     * 生成PhoneNumber
     *
     * @param phone 手机号
     * @return PhoneNumber
     */
    private static Phonenumber.PhoneNumber getPhoneNumber(String phone, Integer countryCode) {
        Phonenumber.PhoneNumber phoneNumber = new Phonenumber.PhoneNumber();
        // 国际长途电话区号  国内 86
        phoneNumber.setCountryCode(countryCode);
        phoneNumber.setNationalNumber(Long.parseLong(phone));
        return phoneNumber;
    }

    /**
     * 生成PhoneNumber
     *
     * @param phone 手机号
     * @return PhoneNumber
     */
    private static Phonenumber.PhoneNumber getChinaPhoneNumber(String phone) {
        return getPhoneNumber(phone, 86);
    }

    public static ChinaRegionInfoDTO getChinaRegionInfoByPhone(String phone) {
        String chinaRegionInfoStr = getChinaRegionInfoStrByPhone(phone);

        Pattern pattern = Pattern.compile("(.*?省)?(.*市)");
        Matcher matcher = pattern.matcher(chinaRegionInfoStr);
        ChinaRegionInfoDTO regionInfoDTO = ChinaRegionInfoDTO.builder().country("中国").build();
        if (matcher.find()) {
            regionInfoDTO.setProvince(matcher.group(1) != null ? matcher.group(1) : matcher.group(2));
            regionInfoDTO.setCity(matcher.group(2));
        }
        return regionInfoDTO;
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ChinaRegionInfoDTO {

        private String country;

        private String province;

        private String city;
    }

}
